package com.hzmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzmall.common.Const;
import com.hzmall.common.RedisShardedPool;
import com.hzmall.common.ServerResponse;
import com.hzmall.dao.UserMapper;
import com.hzmall.pojo.User;
import com.hzmall.service.IUserService;
import com.hzmall.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@Service("userService")
@Slf4j
public class UserService implements IUserService {
    @Autowired
    private UserMapper userMapper;

    //用户登录
    public ServerResponse login(String username, String password) {
        Integer count = this.userMapper.checkUsername(username);
        if (count == 0){
            return ServerResponse.createByErrorCodeMessage(1,"用户名不存在");
        }
        String md5Password = MD5Util.MD5EncodeUtf8(password);
        User user = this.userMapper.login(username, md5Password);
        if (user != null){
            user.setPassword(StringUtils.EMPTY);
            return ServerResponse.createBySuccess(user);
        }
        return ServerResponse.createByErrorCodeMessage(1,"密码错误");
    }

    //用户注册
    public ServerResponse register(User user){
        ServerResponse serverResponse = check_valid(user.getUsername(),Const.USERNAME);
        if (!serverResponse.isSuccess()){
            return serverResponse;
        }
        serverResponse = check_valid(user.getEmail(),Const.EMAIL);
        if (!serverResponse.isSuccess()){
            return serverResponse;
        }
        user.setRole(Const.ROLE.ROLE_CUSTOMER);
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        Integer rows = this.userMapper.insert(user);
        if (rows > 0){
           return ServerResponse.createBySuccessMessage("注册成功");
        }
        return ServerResponse.createByErrorMessage("服务器内部错误");
    }

    //检查用户名或邮箱
    public ServerResponse check_valid(String str, String type){
        if (StringUtils.equals(type,Const.USERNAME)){
            Integer rows = this.userMapper.checkUsername(str);
            if (rows > 0){
                return ServerResponse.createByErrorMessage("用户已存在");
            }
        }
        if (StringUtils.equals(type,Const.EMAIL)){
            Integer rows = this.userMapper.checkUserEmail(str);
            if (rows > 0){
                return ServerResponse.createByErrorMessage("Email已存在");
            }
        }
        return ServerResponse.createBySuccessMessage("校验成功");
    }

    //获取登录用户信息
    public ServerResponse getUserInfo(User user) {
        if (user == null) {
            return ServerResponse.createByErrorMessage("用户未登录,无法获取当前用户信息");
        }
        User currentUser = this.userMapper.selectByPrimaryKey(user.getId());
        return ServerResponse.createBySuccess(currentUser);
    }

    //获取用户重置密码问题
    public ServerResponse forgetGetQuestion(String username){
        if (StringUtils.isBlank(username)){
            return ServerResponse.createByErrorMessage("用户名不能为空");
        }
        ServerResponse response = this.check_valid(username,Const.USERNAME);
        if (response.isSuccess()){
            return ServerResponse.createByErrorMessage("该用户不存在");
        }
        String question = this.userMapper.getForgetQuestion(username);
        if (StringUtils.isBlank(question)){
            return ServerResponse.createByErrorMessage("该用户未设置找回密码问题");
        }
        return ServerResponse.createBySuccess(question);
    }

    //检查提交问题答案
    public ServerResponse forgetCheckAnswer(String username, String question, String answer){
        if (StringUtils.isBlank(username) || StringUtils.isBlank(question) || StringUtils.isBlank(answer)){
            return ServerResponse.createByErrorMessage("参数错误");
        }
        ServerResponse response = this.check_valid(username,Const.USERNAME);
        if (response.isSuccess()){
            return ServerResponse.createByErrorMessage("该用户不存在");
        }
        Integer rows = this.userMapper.checkAnswer(username, question, answer);
        if (rows > 0){
            String token = UUID.randomUUID().toString();
            RedisShardedPoolUtil.setEx(Const.FORGET_TOKEN,token,Const.FORGET_TOKEN_EXPIRE);
            return ServerResponse.createBySuccess(token);
        }
        return ServerResponse.createByErrorMessage("问题答案错误");
    }

    ////忘记密码的重设密码
    public ServerResponse forgetResetPassword(String username, String passwordNew, String forgetToken){
        ServerResponse response = this.check_valid(username, Const.USERNAME);
        if (response.isSuccess()){
            return ServerResponse.createByErrorMessage("该用户不存在");
        }
        String token = RedisShardedPoolUtil.get(Const.FORGET_TOKEN);
        if (StringUtils.isBlank(token)){
            return ServerResponse.createByErrorMessage("token已失效");
        }
        if (!StringUtils.equals(token,forgetToken)){
            return ServerResponse.createByErrorMessage("修改密码操作失败,token不匹配");
        }
        Integer rows = this.userMapper.resetPassword(username,MD5Util.MD5EncodeUtf8(passwordNew));
        if (rows > 0){
            return ServerResponse.createBySuccessMessage("修改密码成功");
        }
        return ServerResponse.createByErrorMessage("修改密码操作失败");
    }

    //登录状态下重置密码
    public ServerResponse resetPassword(String passwordOld,String passwordNew,User user){
        User selectUser = this.userMapper.selectUserByUsernameAndPassword(user.getUsername(),MD5Util.MD5EncodeUtf8(passwordOld));
        if (selectUser == null){
            return ServerResponse.createByErrorMessage("旧密码输入错误");
        }
        selectUser.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
        Integer rows = this.userMapper.updateByPrimaryKeySelective(selectUser);
        if (rows > 0){
            return ServerResponse.createBySuccessMessage("修改密码成功");
        }
        return ServerResponse.createByErrorMessage("修改密码失败!!");
    }

    //登陆状态下修改用户信息
    public ServerResponse updateInformation(User user){
        if (StringUtils.isNotBlank(user.getEmail())){
            ServerResponse response = this.check_valid(user.getEmail(),Const.EMAIL);
            if (!response.isSuccess()){
                return ServerResponse.createByErrorMessage("该Email已存在");
            }
        }
        Integer rows = this.userMapper.updateByPrimaryKeySelective(user);
        if (rows > 0){
            return ServerResponse.createBySuccessMessage("更新个人信息成功");
        }
        return ServerResponse.createByErrorMessage("服务器内部错误");
    }

    //注销
    public ServerResponse logout(HttpServletRequest request, HttpServletResponse response){
        if (CheckLoginUtil.doCheckLogin(request) != null){
            RedisShardedPoolUtil.del(CookieUtil.readCookie(request));
            CookieUtil.deleteCookie(request,response);
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByErrorMessage("当前没有检测到登录信息，无法执行注销操作");
    }



    /**
     * ----------------------------后台逻辑部分------------------------------
     */

    /**
     *后台用户登录
     */
    public ServerResponse adminLogin(HttpServletRequest request, String username,HttpSession session,
                                String password,HttpServletResponse response){
        try {
            User currentUser = CheckLoginUtil.doCheckLogin(request);
            if (currentUser != null){
                logout(request,response);
            }
        } catch (Exception e) {
            log.info("原登录账户登出失败",e);
        }
        User admin = this.userMapper.selectAdminUser(username,MD5Util.MD5EncodeUtf8(password),1);
        if (admin != null){
            CookieUtil.setCookie(response,session.getId());
            RedisShardedPoolUtil.setEx(session.getId(), JsonUtil.obj2String(admin),Const.FORGET_TOKEN_EXPIRE);
            admin.setPassword(StringUtils.EMPTY);
            admin.setQuestion(StringUtils.EMPTY);
            admin.setAnswer(StringUtils.EMPTY);
            return ServerResponse.createBySuccess(admin);
        }
        return ServerResponse.createByErrorMessage("用户名或密码错误");
    }

    //用户列表
    public ServerResponse list(Integer pageNum,Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<User> userList = this.userMapper.selectAllUser();
        List<User> finalUserList = new ArrayList<User>();
        for (User userItem : userList){
            userItem.setPassword(StringUtils.EMPTY);
            if (userItem.getRole() != Const.ROLE.ROLE_ADMIN){
                finalUserList.add(userItem);
            }
        }
        PageInfo pageInfo = new PageInfo(userList);
        pageInfo.setList(finalUserList);
        return ServerResponse.createBySuccess(pageInfo);
    }


}
